package com.twu.biblioteca;

import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class Utils {

    public static HashMap<String, String> findIn(List<HashMap> data, String key, String val) {
        for (HashMap<String, String> d : data) {
            if (d.get(key).equals(val)) return d;
        }
        return new HashMap<String, String>();
    }

    public static String prettyTableFormater(List<HashMap> rows, List<String> excludeCol) {
        StringBuffer output = new StringBuffer();
        Set<String> headers = rows.get(0).keySet();
        for (String exclude:excludeCol){
            headers.remove(exclude);
        }
        for (String header : headers) {
            output.append(header);
            output.append("\t");
        }
        output.append("\n");
        for (HashMap row : rows) {
            for (String header : headers) {
                output.append(row.get(header) == null ? "N/A" : String.valueOf(row.get(header)));
                output.append("\t");
            }
            output.append("\n");
        }
        return output.toString();
    }

    public static HashMap<String, List> loadYamlDB() {
        InputStream input = null;
        try {
            input = new FileInputStream(new File("resources/data.yml"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        Yaml yaml = new Yaml();
        return (HashMap) yaml.load(input);
    }
}